package cj.web.sc.controllers;

import java.io.File;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.utils.Constants;
import cj.utils.ImageUtils;
import cj.utils.ReadConfigProperties;
import cj.utils.ReturnUUID;
import cj.web.constants.MemuEnum;
import cj.web.admin.domain.UserInfo;
import cj.web.login.controllers.BaseController;
import cj.web.marriage.constants.MarriageSCGoodsStatusEnum;
import cj.web.sc.dao.SCCategoryDAO;
import cj.web.sc.dao.SCGoodsDAO;
import cj.web.sc.dao.SCGoodsItemsDAO;
import cj.web.sc.dao.SCPropertyDAO;
import cj.web.sc.dao.SCPropertyValueDAO;
import cj.web.sc.dao.SCSellerDAO;
import cj.web.sc.domain.SCCategory;
import cj.web.sc.domain.SCGoods;
import cj.web.sc.domain.SCGoodsItems;
import cj.web.sc.domain.SCSeller;

@Path("/goods")
public class SCGoodsController extends BaseController{

	private static Logger logger = Logger.getLogger(SCGoodsController.class.getName());
	
	@Autowired
	private SCGoodsDAO goodsDao;
	@Autowired
	private SCSellerDAO sellerDao;
	@Autowired
	private SCCategoryDAO categoryDao;
	@Autowired
	private SCPropertyDAO propertyDAO;
	@Autowired
	private SCPropertyValueDAO proValDAO;
	@Autowired
	private SCGoodsItemsDAO goodsItemsDAO;

	@Get("show")
	public String show(Model model,SCGoods goods, HttpServletRequest request)
	{
		boolean flag = false;
		model.add("StatusEnum",EnumSet.allOf(MarriageSCGoodsStatusEnum.class));
		model.add("MemuEnum", MemuEnum.scgoods);
		UserInfo user =  returnSessionObj(request);
		int userId = user.getId();
		//是否是商家
		SCSeller seller = sellerDao.queryByUserInfoId(userId);
		if(seller!=null){
			flag = true;
		}
		model.add("flag", flag);
		
		return "/views/sc/goodsList.vm";
	}
	
	@Post("list")
	public String list(Model model,SCGoods goods, HttpServletRequest request)
	{
		UserInfo user =  returnSessionObj(request);
		String acount = user.getAccount();
		int userId = user.getId();
		SCSeller seller = sellerDao.queryByUserInfoId(userId);
		
		if(seller != null){
			goods.setSellerId(seller.getId());
		}
		
		if(Constants.ADMIN.equals(acount)){  //admin账户可看到所有的
			goods.setSellerId(-1);
		}
		
		List<Map> objs = goodsDao.queryBySellerId(goods);
		int size = goodsDao.sizeBySellerId(goods);
		
		JSONObject jo = new JSONObject();
		jo.put("data", objs);
		jo.put("draw", goods.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@" + jo.toString();
	}
	
	@Get("create")
	public String create(Model model, HttpServletRequest request)
	{
		UserInfo user =  returnSessionObj(request);
		String acount = user.getAccount();
		int userId = user.getId();
		SCSeller seller = sellerDao.queryByUserInfoId(userId);
		
		if(seller != null){
			model.add("sellerId",seller.getId());
		}
		else if(Constants.ADMIN.equals(acount)){  //admin账户可看到所有的
			model.add("sellerId",-1);
			List<Map> sellers = sellerDao.queryAll();
			model.add("Sellers",sellers);
		}
		
		model.add("MemuEnum", MemuEnum.scgoods);
		return "/views/sc/goodsDetail.vm";
	}
	
	@Post("crtGoods")
	public String crtGoods(Model model,SCGoods goods, @Param("items")String items, @Param("banner")String banner, HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		String account = returnSessionObj(request).getAccount();
		
		goods.setCreateUser(account);
		goods.setUpdateUser(account);
		goods.setDeleteFlag(1);
		String imagePath = goods.getImage();
		String[] paths = imagePath.split("/");
		if(paths != null && paths.length >= 2){
			imagePath = paths[0] + "/ss_" + paths[1].substring(2);
		}
		goods.setImage(imagePath);
		goods.setStatus(MarriageSCGoodsStatusEnum.SPSJ.getValue());
		
		int goodsId = goodsDao.create(goods);
		
		JSONArray arrBanner = JSONArray.fromObject(banner);
		for(int i = 0; i < arrBanner.size(); i++){
			String path = arrBanner.getString(i);
			goodsDao.createBanner(path,goodsId);
		}
		
		JSONArray receiveItems = JSONArray.fromObject(items);
		double minOrignPrice = 0.0;
		double maxOrignPrice = 0.0;
		double minDiscntPrice = 0.0;
		double maxDiscntPrice = 0.0;
		
		for(int i = 0; i < receiveItems.size(); i++){
			SCGoodsItems item = new SCGoodsItems();
			JSONObject receiveItem = receiveItems.getJSONObject(i);
			
			double orignPrice = receiveItem.getDouble("orignPrice");
			double discntPrice = receiveItem.getDouble("discntPrice");
			if(orignPrice > maxOrignPrice){
				maxOrignPrice = orignPrice;
			}
			if(minOrignPrice == 0.0 || orignPrice < minOrignPrice){
				minOrignPrice = orignPrice;
			}
			
			if(discntPrice > maxDiscntPrice){
				maxDiscntPrice = discntPrice;
			}
			if(minDiscntPrice == 0.0 || discntPrice < minDiscntPrice){
				minDiscntPrice = discntPrice;
			}
			
			item.setPropValueIds(receiveItem.getString("propValueIds"));
			item.setPropValueNames(receiveItem.getString("propValueNames"));
			item.setName(receiveItem.getString("name"));
			item.setOrignPrice(orignPrice);
			item.setDiscntPrice(discntPrice);
			item.setInventory(receiveItem.getInt("inventory"));
			item.setImage(imagePath);
			item.setCreateUser(account);
			item.setUpdateUser(account);
			item.setDeleteFlag(1);
			
			item.setGoodsId(goodsId);
			item.setCategoryId(goods.getCategoryId());
			item.setSellerId(goods.getSellerId());
			item.setFreight(0.0);
			item.setSelledCnt(0);
			
			goodsItemsDAO.create(item);
		}
		
		String origPriceRange = "";
		if( minOrignPrice == maxOrignPrice ){
			origPriceRange = String.format("%.2f", maxOrignPrice);
		}
		else{
			origPriceRange = String.format("%.2f - %.2f", minOrignPrice, maxOrignPrice);
		}
		
		String discntPriceRange = "";
		if( minDiscntPrice == maxDiscntPrice ){
			discntPriceRange = String.format("%.2f", maxDiscntPrice);
		}
		else{
			discntPriceRange = String.format("%.2f - %.2f", minDiscntPrice, maxDiscntPrice);
		}
		
		goodsDao.updatePriceRange(goodsId, origPriceRange, discntPriceRange);
		
		return "@" + jo.toString();
	}

	@Get("edit")
	public String edit(Model model, @Param("id") int id, HttpServletRequest request)
	{
		SCGoods obj = goodsDao.queryById(id);
		model.add("obj", obj);
		List<Map> banner = goodsDao.getBannerByGoodsId(id);
		model.add("Banner", banner);
		model.add("MemuEnum", MemuEnum.scgoods);
		return "/views/sc/goodsEdit.vm";
	}
	
	@Post("update")
	public String update(Model model,SCGoods goods,@Param("banner")String banner, HttpServletRequest request)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String acount = returnSessionObj(request).getAccount();
		goods.setUpdateUser(acount);
		
		String imagePath = goods.getImage();
		String[] paths = imagePath.split("/");
		if(paths != null && paths.length >= 2){
			imagePath = paths[0] + "/ss_" + paths[1].substring(2);
		}
		goods.setImage(imagePath);
		
		try {
			goodsDao.update(goods);
		} catch (Exception e) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		//单属性的商品更新item图片
		int goodsId = goods.getId().intValue();
		int itmCnt = goodsItemsDAO.getItmCntByGoodsId(goodsId);
		if(itmCnt <= 1){
			goodsItemsDAO.updateImgByGoodsId(goodsId, imagePath);
		}
		
		//更新轮播图
		JSONArray arrBanner = JSONArray.fromObject(banner);
		goodsDao.delBannerByGoodsId(goodsId);
		for(int i = 0; i < arrBanner.size(); i++){
			String path = arrBanner.getString(i);
			goodsDao.createBanner(path,goodsId);
		}
		
		return "@" + jo.toString();
	}
	
	@Get("deleteById")
	public String deleteById(Model model,@Param("id") int id, HttpServletRequest request)
	{
		SCGoods goods = goodsDao.queryById(id);
		if(goods != null){
			String acount = returnSessionObj(request).getAccount();
			
			goods.setUpdateUser(acount);
			goodsDao.deleteById(goods);
			goodsItemsDAO.deleteByGoodsId(id);  //删除商品详情
			goodsItemsDAO.chgCartByGoodsId(id,0); //购物车失效
		}
		
		return "r:show";
	}
	
	@Get("updown")//上下架
	public String updown(Model model,@Param("id") int id, HttpServletRequest request)
	{
		SCGoods goods = goodsDao.queryById(id);
		if(goods != null){
			String acount = returnSessionObj(request).getAccount();
			goods.setUpdateUser(acount);
			
			if(MarriageSCGoodsStatusEnum.SPSJ.getValue() == goods.getStatus()){
				goods.setStatus(MarriageSCGoodsStatusEnum.SPXJ.getValue());
				goodsItemsDAO.deleteByGoodsId(id); //商品详情下架
				goodsItemsDAO.chgCartByGoodsId(id,0); //购物车失效
			}
			else{
				goods.setStatus(MarriageSCGoodsStatusEnum.SPSJ.getValue());
				goodsItemsDAO.validateByGoodsId(id); //商品详情上架
				goodsItemsDAO.chgCartByGoodsId(id,1); //购物车有效
			}
			
			goodsDao.updownById(goods);
		}
		
		return "r:show";
	}
	
	@Get("stick")//置顶
	public String stick(Model model,@Param("id") int id)
	{
		SCGoods goods = goodsDao.queryById(id);
		if(goods != null){
			goodsDao.stick(id);
		}
		
		return "r:show";
	}
	
	@Post("initCategory")//初始化类型
	public String initCategory(@Param("categoryIds")String ids){
		JSONObject jo = new JSONObject();
		List<Map> rets = new ArrayList<Map>();
		
		List<SCCategory> categories = categoryDao.queryAllObjs();
		for(SCCategory category : categories){
			Map ret = new HashMap<>();
			
			ret.put("id", category.getId());
			ret.put("pId", category.getParentId());
			ret.put("name", category.getName());
			ret.put("open", true);
			
			if(ids != null && ids.length() > 0){
				String[] categoryIds = ids.split(",");
				for( String categoryId :  categoryIds){
					if( Integer.parseInt(categoryId) == category.getId().intValue()){
						ret.put("checked", true);
						break;
					}
					ret.put("checked", false);
				}
			}
			else{
				ret.put("checked", false);
			}
			
			rets.add(ret);
		}
		
		jo.put("ret", rets);
		
		return "@" + jo.toString();
	}
	
	@Post("getProByCategory")
	public String getProByCategory(@Param("categoryId")int categoryId){
		JSONObject jo = new JSONObject();

		List<Map> objs = propertyDAO.queryByCategoryId(categoryId);
		for(Map obj : objs){
			int propertyId = Integer.parseInt(obj.get("id").toString());
			List<Map> vals = proValDAO.queryByPropertyId(propertyId);
			obj.put("vals", vals);
		}
		
		jo.put("objs", objs);
		
		return "@"+jo.toString();
	}
	
	@Post("upload")
    public String upload(@Param("uploadimage")MultipartFile file) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		// 判断文件是否为空  
        if (file != null && !file.isEmpty()) {  
            try {  
            	// 文件保存路径  
            	String path = ReadConfigProperties.getValue("uploadFilePath");
            	//判断文件是否存在，不存在创建文件
            	Map rep = ReturnUUID.getFolder(path);
            	path = rep.get("allpath").toString();//所在的全路径
            	//文件名
                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
                // 转存文件  
                file.transferTo(new File(path+"/"+fileName));
                
                ImageUtils.scale3(path+"/"+fileName, path+"/b_"+fileName, 600, 750);//切图 750 * 600
                
                ImageUtils.scale3(path+"/"+fileName, path+"/q_"+fileName, 246, 246);//切图 246 * 246
                
                ImageUtils.scale2(path+"/b_"+fileName, path+"/s_"+fileName, 600, 750, true);//缩率图		750 * 600
                
                ImageUtils.scale2(path+"/q_"+fileName, path+"/ss_"+fileName, 246, 246, true);//缩率图		246*246
                
                
                ImageUtils.scale2(path+"/"+fileName, path+"/pcs_"+fileName, 480, 660, true);//缩率图 660 * 480
                
                ImageUtils.scale2(path+"/"+fileName, path+"/pcss_"+fileName, 116, 156, true);//缩率图 156 * 116
                
                jo.put("filePath", rep.get("filepath")+"/s_"+fileName);
                
                
            } catch (Exception e) {
                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
            }  
        } 
		
		return "@"+jo.toString();
    }
	

}
